package com.cantor.provider.start;

import cn.hutool.core.util.ObjectUtil;
import com.cantor.common.exception.ComponentLackException;
import com.cantor.common.exception.NettyStartException;
import com.cantor.common.util.CantorUtil;
import com.cantor.core.center.RegistrationCenter;
import com.cantor.core.config.CantorAppConfig;
import com.cantor.core.config.CantorAppConfigProperties;
import com.cantor.provider.regsitry.ServiceRegistrant;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;

/**
 * 服务提供方启动器
 */
@Slf4j
@Builder
public class ProviderBootstrap {

    // 全局配置类
    private CantorAppConfig appConfig;

    // 远程注册中心
    private RegistrationCenter center;

    // 服务注册器(Map的维护者)
    private ServiceRegistrant serviceRegistrant;

    // 启动Cantor Provider
    public void start() throws Exception {
        // 1.检查组件是否齐全
        if (ObjectUtil.isNull(appConfig)) {
            log.error("缺少CantorAppConfig, 服务提供者启动失败");
            throw new ComponentLackException();
        }
        if (ObjectUtil.isNull(center)) {
            log.error("缺少RegistrationCenter, 服务提供者启动失败");
            throw new ComponentLackException();
        }
        if (ObjectUtil.isNull(serviceRegistrant)) {
            log.error("缺少ServiceRegistrant, 服务提供者启动失败");
            throw new ComponentLackException();
        }
        // 2.根据配置文件配置的端口启动ProviderNettyMaintainer
        CantorAppConfigProperties properties = appConfig.getProperties();
        ProviderNettyKeeper providerNettyKeeper = new ProviderNettyKeeper(properties.getHost(),properties.getPort(), serviceRegistrant);
        boolean isSuccess = providerNettyKeeper.run();
        if (!isSuccess) {
            throw new NettyStartException();
        }
        // 3.启动成功后, 初始化并启动远程注册中心.
        center.run();
        // 4.将服务全部注册到远程注册中心
        serviceRegistrant.registerAllServicesToCenter(appConfig,center);
        // 5.打印Logo
        CantorUtil.printCantorLogo();
        log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        log.info("+++++++++++++++++ [服务提供者 {}] 已经运行于 {}:{} ++++++++++++++++++", properties.getAppName(), CantorUtil.getExactLocalHost(), properties.getPort());
        log.info("+++++++++++++++ [ Provider {}] is running at {}:{} ++++++++++++++", properties.getAppName(), CantorUtil.getExactLocalHost(), properties.getPort());
        log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
    }

}
